import 'package:flutter/material.dart';
import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/bloc/my/attentionOrFansBloc.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/models/attentionModel.dart';
import 'package:qgchat/http/models/fansModel.dart';
import 'package:qgchat/http/models/userInfoModel.dart';
import 'package:qgchat/states/states_model/socket.dart';
import 'package:qgchat/widgets/appbarCustom.dart';
import 'package:qgchat/widgets/avatar.dart';
import 'package:qgchat/widgets/line.dart';

///
/// 关注or粉丝页面
/// page关注or粉丝
///

class AttentionOrFans extends StatefulWidget {
  @override
  _AttentionOrFansState createState() => _AttentionOrFansState();
}

class _AttentionOrFansState extends State<AttentionOrFans> {
  final blog = AttentionOrFansBloc();

  String pageType; // 页面类型

  String getAppbarTitle() {
    if (pageType == 'attention')
      return '关注';
    else if (pageType == 'fans') return '粉丝';
    return '';
  }

// -----------------------------------------------------------------------------

  /// appbar
  Widget appBar() {
    return AppbarCustom(getAppbarTitle());
  }

  /// 关注or粉丝列表
  Widget attentionOrFansList() {
    final AttentionOrFansBloc bloc =
        BlocProvider.of<AttentionOrFansBloc>(context);
    Stream blocStream;
    if (pageType == 'attention') {
    } else if (pageType == 'fans') {
      blocStream = bloc.outFansStream;
    }

    return StreamBuilder<List<FansModel>>(
      stream: blocStream,
      initialData: [],
      builder: (BuildContext context, AsyncSnapshot<List<FansModel>> snapshot) {
        return Text(snapshot.toString());
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return stateBuilder(context, 'user', (user) {
      UserInfoModel userInfo = user.info;
      if (userInfo != null) {
        print(userInfo.memberType);
        if (userInfo.memberType == 0) {
          pageType = 'attention';
        } else {
          pageType = 'fans';
        }

        return BlocProvider<AttentionOrFansBloc>(
          bloc: blog,
          child: Scaffold(
            appBar: appBar(),
            body: Container(
              width: w100(context),
              padding: EdgeInsets.symmetric(horizontal: px(30)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  /// 关注or粉丝人数
                  _AllNum(pageType),

                  /// 关注or粉丝列表
                  Container(
                      child: Expanded(
                    child: SingleChildScrollView(
                      physics: BouncingScrollPhysics(),
                      child: SafeArea(
                        bottom: true,
                        child: _AttentionOrFansList(pageType),
                      ),
                    ),
                  ))
                ],
              ),
            ),
          ),
        );
      } else {
        return Scaffold(
          body: Container(),
        );
      }
    });
  }
}

/// 总计
class _AllNum extends StatelessWidget {
  _AllNum(this.pageType, {Key key}) : super(key: key);
  String pageType;

  String getAppbarTitle() {
    if (pageType == 'attention')
      return '关注';
    else if (pageType == 'fans') return '粉丝';
    return '';
  }

  @override
  Widget build(BuildContext context) {
    final AttentionOrFansBloc bloc =
        BlocProvider.of<AttentionOrFansBloc>(context);
    Stream blocStream;
    if (pageType == 'attention') {
      blocStream = bloc.outAttentionStream;
    } else if (pageType == 'fans') {
      blocStream = bloc.outFansStream;
    }
    return StreamBuilder(
      stream: blocStream,
      initialData: null,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.data != null) {
          return Container(
            margin: EdgeInsets.only(top: px(20)),
            child: Text.rich(
              TextSpan(
                children: [
                  TextSpan(
                    text: getAppbarTitle() + '  ',
                    style: TextStyle(fontSize: px(28), color: col('909399')),
                  ),
                  TextSpan(
                    text: snapshot.data.length.toString(),
                    style: TextStyle(
                      fontSize: px(28),
                      color: col('303133'),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
          );
        } else {
          return Container();
        }
      },
    );
  }
}

/// 列表
class _AttentionOrFansList extends StatelessWidget {
  _AttentionOrFansList(this.pageType, {Key key}) : super(key: key);

//  String pageType = 'fans'; // 页面类型
  final String pageType;

  // 私信按钮
  void _privateLetterClick(
    context,
    id,
    userName,
    avatar,
    token,
  ) {
    SocketState socketState = (state(Global.context, 'socket') as SocketState);
    socketState.goChatPage(
      context,
      id: id,
      token: token,
      name: userName,
      head: avatar,
    );
  }

  /// 关注or粉丝列表单项构造器
  Widget _attentionOrFansListItemBuilder(
    context,
    String token,
    String userName,
    int id,
    String avatar, {
    int gold,
    String sign,
  }) {
    /// 签名或粉丝
    Widget _signatureOrGold() {
      if (pageType == 'attention') {
        return Container(
          child: Text(
            sign,
            style: TextStyle(fontSize: px(26), color: col('909399')),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        );
      } else {
        return Container(
          child: Row(
            children: <Widget>[
              Container(
                width: px(32),
                height: px(32),
                margin: EdgeInsets.only(right: px(11)),
                child: Image.asset('assets/images/icon/star.png'),
              ),
              Container(
                child: Text(
                  '$gold',
                  style: TextStyle(fontSize: px(28), color: col('fea800')),
                ),
              )
            ],
          ),
        );
      }
    }

    /// 按钮
    Widget _button(context) {
      if (pageType == 'attention') {
        return Container(
          height: px(60),
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(horizontal: px(23)),
          decoration: BoxDecoration(
            color: col('edeff2'),
            borderRadius: BorderRadius.circular(
              px(30),
            ),
          ),
          child: Text(
            '已关注',
            style: TextStyle(
              fontSize: px(26),
              color: col('303133'),
              height: 1.2,
            ),
          ),
        );
      } else {
        return Container(
          height: px(60),
          width: px(120),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(px(30)),
            border: Border.all(color: col('fea800'), width: px(2)),
          ),
          child: FlatButton(
            padding: EdgeInsets.zero,
            onPressed: () {
              _privateLetterClick(
                context,
                id,
                userName,
                avatar,
                token,
              );
            },
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(
                Radius.circular(px(30)),
              ),
            ),
            child: Text(
              '私信',
              style: TextStyle(
                fontSize: px(26),
                color: col('fea800'),
                height: 1.2,
              ),
            ),
          ),
        );
      }
    }

    return Container(
      child: Column(
        children: <Widget>[
          Container(
            height: px(168),
            child: Row(
              children: <Widget>[
                /// 头像
                Container(
                  margin: EdgeInsets.only(right: px(20)),
                  child: Avatar(
                    avatar,
                    true,
                    token: token,
                  ),
                ),

                /// 用户信息
                Container(
                  width: px(363),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      /// 用户名与ID
                      Container(
                        margin: EdgeInsets.only(bottom: px(10)),
                        child: Text.rich(
                          TextSpan(
                            children: [
                              TextSpan(
                                text: userName + '  ',
                                style: TextStyle(
                                  fontSize: px(28),
                                  color: col('303133'),
                                ),
                              ),
                              TextSpan(
                                text: 'ID:${id.toString()}',
                                style: TextStyle(
                                  fontSize: px(24),
                                  color: col('bfc2cc'),
                                ),
                              )
                            ],
                          ),
                        ),
                      ),

                      /// 签名或粉丝
                      _signatureOrGold()
                    ],
                  ),
                ),

                /// 按钮
                Container(
                  margin: EdgeInsets.only(left: px(68)),
                  child: _button(context),
                ),
              ],
            ),
          ),

          /// 分割线
          Line(
            margin: EdgeInsets.only(left: px(138)),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final AttentionOrFansBloc bloc =
        BlocProvider.of<AttentionOrFansBloc>(context);
    Stream blocStream;
    if (pageType == 'attention') {
      blocStream = bloc.outAttentionStream;
      bloc.getAttentionList();

      return StreamBuilder<List<AttentionModel>>(
        stream: blocStream,
        initialData: [],
        builder: (
          BuildContext context,
          AsyncSnapshot<List<AttentionModel>> snapshot,
        ) {
          return Container(
            child: Column(
              children: snapshot.data.map<Widget>((item) {
                return _attentionOrFansListItemBuilder(
                  context,
                  item.memberToken,
                  item.memberNickname,
                  int.parse(item.uid),
                  item.memberHead,
                  sign: item.anchorSign,
                );
              }).toList(),
            ),
          );
        },
      );
    } else if (pageType == 'fans') {
      blocStream = bloc.outFansStream;
      bloc.getFansList();

      return StreamBuilder<List<FansModel>>(
        stream: blocStream,
        initialData: [],
        builder:
            (BuildContext context, AsyncSnapshot<List<FansModel>> snapshot) {
          return Container(
            child: Column(
              children: snapshot.data.map<Widget>((item) {
                return _attentionOrFansListItemBuilder(
                  context,
                  item.memberToken,
                  item.memberNickname,
                  item.id,
                  item.memberHead,
                  gold: item.gold,
                );
              }).toList(),
            ),
          );
        },
      );
    }
  }
}
